package net.hserver.admin.system.utils;


import cn.hserver.mvc.context.WebContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.lionsoul.ip2region.xdb.Searcher;

import java.io.*;
@Slf4j
public class IpUtil {
    private static Searcher ipSearcher;


    public static String getIp(String ip) {
        try {
            if (ipSearcher == null) {
                ipSearcher = Searcher.newWithBuffer(data());
            }
            return ipSearcher.search(ip);
        } catch (Exception e) {
           log.error(e.getMessage(), e);
        }
        return "";
    }

    public static String getIp() {
        return getIp(WebContextHolder.getWebContext().request.getIpAddress());
    }

    private static byte[] data() {
        try {
            InputStream is = IpUtil.class.getResourceAsStream("/ip2region.xdb");
            try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
                byte[] buffer = new byte[1024];
                int bytesRead;
                if (is != null) {
                    while ((bytesRead = is.read(buffer)) != -1) {
                        byteArrayOutputStream.write(buffer, 0, bytesRead);
                    }
                }
                return byteArrayOutputStream.toByteArray();
            }
        } catch (IOException var6) {
            log.error(var6.getMessage(), var6);
            return null;
        }
    }

}
